package com.qiku.web.filter;

import com.qiku.pojo.User;
import com.qiku.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebFilter(filterName = "loginFilter", urlPatterns = "/login")
public class LoginFilter implements Filter {

    //声明一个 ServletContext
    private ServletContext context = null;

    /**
     * 初始化 LoginFilter 的时候  执行的方法
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取ServletContext 给context  赋值
        context = filterConfig.getServletContext();
        //准备一个Map 用于保存用户名和sessionID  并将该Map 绑定在context中
        Map<String, String> userLoginMap = new HashMap<>();
        context.setAttribute("userLoginMap", userLoginMap);
    }

    /**
     * 定义  拦截到请求之后  具体的执行逻辑
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            //解决中文乱码
            servletRequest.setCharacterEncoding("utf-8");
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            // 1 获取用户名username和password
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //调用方法判断username和password正不正确
            User user = new UserServiceImpl().userLogin(username, password);
            if (user != null) {
                // 2 检查userLoginMap 中是否存在  key = username
                Map<String, String> userLoginMap = (Map<String, String>) context.getAttribute("userLoginMap");
                if (userLoginMap.containsKey(username)) {
                    // 3 如果存在 => 已登录
                    // 3.1 获取 userLoginMap 中 username对应的sessionID sid01
                    String sid01 = userLoginMap.get(username);
                    // 3.2 获取当前的sessionID sid02
                    String sid02 = request.getSession().getId();
                    // 3.3 如果sid01 != sid02 说明是异地登陆
                    if (!sid01.equals(sid02)) {
                        // 则 将sid02 替换掉 sid01 ==> userLoginMap.put(username,sid02)
                        userLoginMap.put(username, sid02);
                    }
                } else {
                    // 4 如果不存在 => 第一次登录，则 获取sessionID 与 username 存入userLoginMap
                    userLoginMap.put(username, request.getSession().getId());
                }
            }
            // 5 放行
            filterChain.doFilter(request, servletResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * LoginFilter  销毁的过程  自杀的方式
     */
    @Override
    public void destroy() {

    }
}
